/*
* jlb
*/
package com.jlb.user.ctrl;

import com.alibaba.fastjson.JSON;
import com.jlb.core.entity.BeanRet;
import com.jlb.core.entity.Page;
import com.jlb.core.exceptions.BaseException;
import com.jlb.core.tools.DateTools;
import com.jlb.core.tools.JwtToken;
import com.jlb.core.tools.redis.RedisUtils;
import com.jlb.setting.entity.Setting;
import com.jlb.setting.service.SettingSV;
import com.jlb.user.entity.*;
import com.jlb.user.service.UserJlbSV;
import com.jlb.user.service.UserMinerSV;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户购买的矿机 控制器
 *
 * @author jlb
 */
@RestController
@RequestMapping("/userMiner")
@Slf4j
@Api(value = "用户购买的矿机控制器", description = "用户购买的矿机控制器")
public class UserMinerCtrl {

    @Resource
    protected RedisUtils redisUtils;

    @Resource
    private SettingSV settingSV;

    @Resource
    private UserMinerSV userMinerSV;

    @Resource
    private UserJlbSV userJlbSV;


    /**
     * 获取调度token接口（仅用于定时调度）
     */
    @ApiOperation(value = "已挖到 （仅用于定时调度）", notes = "已挖到 （仅用于定时调度）")
    @GetMapping(value = "/jobtoken")
    @ResponseBody
    public String genJobToken() {
        String Job_Token_Secret_Key = settingSV.loadByK(Setting.Key.Job_Token_Secret_Key.name()).getV();
        String jobToken = JwtToken.createToken(Job_Token_Secret_Key, 1);
        return jobToken;
    }


    /**
     * 已挖到 （仅用于定时调度）
     */
    @ApiOperation(value = "已挖到 （仅用于定时调度）", notes = "已挖到 （仅用于定时调度）")
    @GetMapping(value = "/digOut")
    @ResponseBody
    public BeanRet digOut(String token) {
        if (StringUtils.isBlank(token)) {
            return BeanRet.create();
        }
        String Job_Token_Secret_Key = settingSV.loadByK(Setting.Key.Job_Token_Secret_Key.name()).getV();
        boolean flag = JwtToken.verifier(token, Job_Token_Secret_Key);
        if (!flag) {
            return BeanRet.create(false, BaseException.BaseExceptionEnum.Job_Token_Verifier_Failed);
        }
//        String checkKey = DateTools.dateToNum8(new Date());
//        if (redisUtils.hasKey(checkKey)) {
//            return BeanRet.create(false, checkKey + " 已经被调度，无需重复调度");
//        } else {
//            redisUtils.set(checkKey, checkKey, 86400);
//        }

        //工作日判断
        if (DateTools.isAllWorkday(DateTools.format(new Date(), "YYYY-MM-dd"))) {
            userJlbSV.mining();


//            Page<UserJlb> page = new Page<>();
//            int count = userJlbSV.count(new HashedMap());
//            page.setTotalRow(count);
//            for (int i = 1; i <= page.getTotalPage(); i++) {
//                page.setCurPage(1);
//                Map<String, Object> param = new HashMap<>();
//                param.put("state", UserJlbState.Active.name());
//                param.put("digInJlbState", UserJlbMinerState.Dig_In.name());
//                List<UserJlb> userJlbList = userJlbSV.list(param, page.genRowStart(), page.getPageSize());
//                page.setVoList(userJlbList);
//                for (UserJlb userJlb : userJlbList) {
//                    try {
//                        userJlbSV.digOut(userJlb.getUserCode());
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        log.error(e.getMessage());
//                    }
//                }
//            }
//
//            //自动收割
//            Map<String, Object> param = new HashMap<>();
//            param.put("state", UserMinerState.Working.name());
//            List<UserMiner> userMinerList = userMinerSV.list(param);
//            userMinerList.forEach(userMiner -> {
//                Map<String, Object> paramUserJlb = new HashMap<>();
//                paramUserJlb.put("userCode", userMiner.getUserCode());
//                paramUserJlb.put("state", UserJlbState.Active.name());
//                paramUserJlb.put("digInJlbState", UserJlbMinerState.Dig_Out.name());
//                UserJlb userJlb = userJlbSV.load(paramUserJlb);
//                if (userJlb != null) {
//                    try {
//                        userJlbSV.harvest(userJlb.getUserCode());
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        log.error(e.getMessage());
//                    }
//                }
//            });

        } else {
            log.info("非工作日矿机无法运行");
        }
        return BeanRet.create(true, "查询成功");
    }


    /**
     * 点击收割金兰宝
     *
     * @return 分页对象
     */
    @ApiOperation(value = "点击收割金兰宝", notes = "点击收割金兰宝")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userCode", value = "用户编码", required = true, paramType = "query")
    })
    @PutMapping(value = "/harvest")
    @ResponseBody
    public BeanRet harvest(String userCode) {
        if (StringUtils.isBlank(userCode)) {
            return BeanRet.create();
        }
        userJlbSV.harvest(userCode);
        return BeanRet.create(true, "查询成功");
    }


    /**
     * 查询UserMiner一个详情信息
     *
     * @param id
     * @param userCode 用户编码
     * @return BeanRet
     */
    @ApiOperation(value = "查询UserMiner一个详情信息", notes = "查询UserMiner一个详情信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", dataType = "java.lang.Long", paramType = "query"),
            @ApiImplicitParam(name = "userCode", value = "用户编码", dataType = "java.lang.String", paramType = "query")
    })
    @GetMapping(value = "/load")
    @ResponseBody
    public BeanRet load(java.lang.Long id, java.lang.String userCode) {
        if (id == null) {
            return null;
        }
        if (userCode == null) {
            return null;
        }
        UserMiner userMiner = userMinerSV.load(id, userCode);
        log.info(JSON.toJSONString(userMiner));
        return BeanRet.create(true, "查询成功", userMiner);
    }


    /**
     * 根据条件id查询UserMiner一个详情信息
     *
     * @param id
     * @return BeanRet
     */
    @ApiOperation(value = "查询UserMiner一个详情信息", notes = "查询UserMiner一个详情信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", dataType = "java.lang.Long", paramType = "path")
    })
    @GetMapping(value = "/load/id/{id}")
    @ResponseBody
    public BeanRet loadById(@PathVariable java.lang.Long id) {
        if (id == null) {
            return null;
        }
        UserMiner userMiner = userMinerSV.loadById(id);
        log.info(JSON.toJSONString(userMiner));
        return BeanRet.create(true, "查询成功", userMiner);
    }

    /**
     * 根据条件userCode查询UserMiner一个详情信息
     *
     * @param userCode 用户编码
     * @return BeanRet
     */
    @ApiOperation(value = "查询UserMiner一个详情信息", notes = "查询UserMiner一个详情信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userCode", value = "用户编码", dataType = "java.lang.String", paramType = "path")
    })
    @GetMapping(value = "/load/userCode/{userCode}")
    @ResponseBody
    public BeanRet loadByUserCode(@PathVariable java.lang.String userCode) {
        if (userCode == null) {
            return null;
        }
        UserMiner userMiner = userMinerSV.loadByUserCode(userCode);
        log.info(JSON.toJSONString(userMiner));
        return BeanRet.create(true, "查询成功", userMiner);
    }


    /**
     * 查询UserMiner信息集合
     *
     * @return 分页对象
     */
    @ApiOperation(value = "查询UserMiner信息集合", notes = "查询UserMiner信息集合")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "curPage", value = "当前页", required = true, paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", required = true, paramType = "query"),
            @ApiImplicitParam(name = "createTimeBegin", value = "购买时间", paramType = "query"),
            @ApiImplicitParam(name = "createTimeEnd", value = "购买时间", paramType = "query"),
            @ApiImplicitParam(name = "updateTimeBegin", value = "更新时间", paramType = "query"),
            @ApiImplicitParam(name = "updateTimeEnd", value = "更新时间", paramType = "query"),
    })
    @GetMapping(value = "/list")
    @ResponseBody
    public BeanRet list(@ApiIgnore UserMiner userMiner, Integer curPage, Integer pageSize) {
        Page<UserMiner> page = new Page<UserMiner>(pageSize, curPage);
        List<UserMiner> userMiners = userMinerSV.list(userMiner, page.genRowStart(), page.getPageSize());
        page.setVoList(userMiners);
        int total = userMinerSV.count(userMiner);
        page.setTotalRow(total);

        return BeanRet.create(true, "查询成功", page);

    }


    /**
     * 查询UserMiner信息集合
     *
     * @return 分页对象
     */
    @ApiOperation(value = "查询UserMiner信息集合", notes = "查询UserMiner信息集合")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "curPage", value = "当前页", required = true, paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", required = true, paramType = "query"),
            @ApiImplicitParam(name = "id", value = "", paramType = "query"),
            @ApiImplicitParam(name = "userCode", value = "用户编码", paramType = "query")
    })
    @GetMapping(value = "/list/by")
    @ResponseBody
    public BeanRet listByPk(java.lang.Long id, java.lang.String userCode, Integer curPage, Integer pageSize) {
        Page<UserMiner> page = new Page<UserMiner>(pageSize, curPage);
        List<UserMiner> userMiners = userMinerSV.list(id, userCode, page.genRowStart(), page.getPageSize());
        page.setVoList(userMiners);
        int total = userMinerSV.count(id, userCode);
        page.setTotalRow(total);

        return BeanRet.create(true, "查询成功", page);
    }

    /**
     * 统计UserMiner信息数量根据主键
     *
     * @return 总条数
     */
    @ApiOperation(value = " 统计UserMiner信息数量根据主键", notes = " 统计UserMiner信息数量根据主键")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", paramType = "query"),
            @ApiImplicitParam(name = "userCode", value = "用户编码", paramType = "query")
    })
    @GetMapping(value = "/count/by")
    @ResponseBody
    public Integer count(java.lang.Long id, java.lang.String userCode) {
        return userMinerSV.count(id, userCode);
    }

    /**
     * 统计UserMiner信息数量
     *
     * @return 总条数
     */
    @ApiOperation(value = "统计UserMiner信息数量", notes = "统计UserMiner信息数量")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", paramType = "query"),
            @ApiImplicitParam(name = "userCode", value = "用户编码", paramType = "query"),
            @ApiImplicitParam(name = "minerCode", value = "矿机编码", paramType = "query"),
            @ApiImplicitParam(name = "dailyIncome", value = "日收益", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "状态：工作中 Working，已停机 Stop", paramType = "query"),
            @ApiImplicitParam(name = "createTime", value = "购买时间", paramType = "query"),
            @ApiImplicitParam(name = "updateTime", value = "更新时间", paramType = "query"),
            @ApiImplicitParam(name = "power", value = "算力", paramType = "query"),
            @ApiImplicitParam(name = "upperLimit", value = "挖矿上限", paramType = "query"),
            @ApiImplicitParam(name = "multiple", value = "上限倍数", paramType = "query")
    })
    @GetMapping(value = "/count")
    @ResponseBody
    public Integer count(@ApiIgnore UserMiner userMiner) {
        if (userMiner == null) {
            return userMinerSV.count(new HashMap());
        } else {
            return userMinerSV.count(userMiner);
        }
    }


    /**
     * 创建UserMiner
     *
     * @return BeanRet
     */
    @ApiOperation(value = "创建UserMiner", notes = "创建UserMiner")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "minerCode", value = "矿机编码", paramType = "query"),
            @ApiImplicitParam(name = "dailyIncome", value = "日收益", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "状态：工作中 Working，已停机 Stop", paramType = "query"),
            @ApiImplicitParam(name = "createTime", value = "购买时间", paramType = "query"),
            @ApiImplicitParam(name = "updateTime", value = "更新时间", paramType = "query"),
            @ApiImplicitParam(name = "power", value = "算力", paramType = "query"),
            @ApiImplicitParam(name = "upperLimit", value = "挖矿上限", paramType = "query"),
            @ApiImplicitParam(name = "multiple", value = "上限倍数", paramType = "query")
    })
    @PostMapping("/build")
    @ResponseBody
    public BeanRet build(@ApiIgnore UserMiner userMiner) {
        userMinerSV.save(userMiner);
        return BeanRet.create(true, "创建成功", userMiner);
    }


    /**
     * 修改UserMiner
     *
     * @return BeanRet
     */
    @ApiOperation(value = "修改UserMiner", notes = "修改UserMiner")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", paramType = "query"),
            @ApiImplicitParam(name = "userCode", value = "用户编码", paramType = "query"),
            @ApiImplicitParam(name = "minerCode", value = "矿机编码", paramType = "query"),
            @ApiImplicitParam(name = "dailyIncome", value = "日收益", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "状态：工作中 Working，已停机 Stop", paramType = "query"),
            @ApiImplicitParam(name = "createTime", value = "购买时间", paramType = "query"),
            @ApiImplicitParam(name = "updateTime", value = "更新时间", paramType = "query"),
            @ApiImplicitParam(name = "power", value = "算力", paramType = "query"),
            @ApiImplicitParam(name = "upperLimit", value = "挖矿上限", paramType = "query"),
            @ApiImplicitParam(name = "multiple", value = "上限倍数", paramType = "query")
    })
    @PutMapping("/modify")
    @ResponseBody
    public BeanRet modify(@ApiIgnore UserMiner userMiner) {
        userMinerSV.modify(userMiner);
        return BeanRet.create(true, "修改成功", userMiner);
    }

    /**
     * 销毁用户矿机 (JOB 调度使用)
     *
     * @return BeanRet
     */
    @ApiOperation(value = "删除UserMiner", notes = "删除UserMiner")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", paramType = "query"),
            @ApiImplicitParam(name = "userCode", value = "用户编码", paramType = "query")
    })
    @GetMapping("/delete")
    @ResponseBody
    public BeanRet delete(String token) {
        if (StringUtils.isBlank(token)) {
            return BeanRet.create();
        }
        String Job_Token_Secret_Key = settingSV.loadByK(Setting.Key.Job_Token_Secret_Key.name()).getV();
        boolean flag = JwtToken.verifier(token, Job_Token_Secret_Key);
        if (!flag) {
            return BeanRet.create(false, BaseException.BaseExceptionEnum.Job_Token_Verifier_Failed);
        }


        log.info("开始删除没有复投超时的矿机");
        Setting setting = settingSV.loadByK(Setting.Key.Delete_Miner_Days.name());
        Page<UserMiner> page = new Page<>();
        int count = userJlbSV.count(new HashedMap());
        page.setTotalRow(count);
        for (int i = 1; i <= page.getTotalPage(); i++) {
            page.setCurPage(1);
            Map<String, Object> param = new HashMap<>();
            param.put("state", UserMinerState.Stop.name());
            List<UserMiner> userMinerList = userMinerSV.list(param, page.genRowStart(), page.getPageSize());
            page.setVoList(userMinerList);
            log.debug("停机矿机集合第" + page.getCurPage() + "页:" + JSON.toJSONString(userMinerList));
            for (UserMiner userMiner : userMinerList) {
                try {
                    Date date = DateTools.calculateByDate(new Date(), -(Integer.parseInt(setting.getV())));
                    String formatDate = DateTools.dateToNum8(date);
                    String updateDate = DateTools.dateToNum8(userMiner.getUpdateTime());
                    if (formatDate.equals(updateDate)) {
                        userMinerSV.delete(null, userMiner.getUserCode());
                        param.clear();
                        param.put("userCode", userMiner.getUserCode());
                        UserJlb userJlb = userJlbSV.load(param);
                        userJlb.setDigInTotalJlb(0);
                        userJlb.setDigInJlb("0");
                        userJlb.setDigInJlbState(UserJlbMinerState.Dig_In.name());
                        userJlbSV.saveOrUpdate(userJlb);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error(e.getMessage());
                }
            }
        }


        return BeanRet.create(true, "删除UserMiner成功");
    }

}
